package com.example.pc.myapplication;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements SensorEventListener {
  //  TextView view;
    //TextView view2;

    SensorManager sensorManager;
    Sensor sensor;
    ImageView imageView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    protected void onStart(){
        super.onStart();
       // view =findViewById(R.id.textView1);
     //   view2=findViewById(R.id.textView2);
        imageView=findViewById(R.id.imageView1);

        //注册监听
        sensorManager= (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
        sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_NORMAL);
    }

    @Override
    public void onSensorChanged(SensorEvent var1){

        //加速度传感器
      //  https://blog.csdn.net/feixiaku/article/details/45136525
        if (var1.sensor.getType() == Sensor.TYPE_ACCELEROMETER){
            float x= var1.values[0];
            float y= var1.values[1];
            float z= var1.values[2];

         //   view.setText(x+"  "+y+"   "+z);
        }
        //磁场传感器
        if(var1.sensor.getType() == Sensor.TYPE_ORIENTATION){
            float x= var1.values[0];
//            float y= var1.values[1];
//            float z= var1.values[2];

         //   view2.setText("");
            imageView.setRotation(360-x);
        }


   //    view.setText();
    }
    @Override
    public void onAccuracyChanged(Sensor var1, int var2){

    }
}
